//
//  UIImage+LHAdd.m
//  Loohoo
//
//  Created by 陈镇 on 2025/3/19.
//

#import "UIImage+LHAdd.h"
#import "UIImage+QMUI.h"

@implementation UIImage (LHAdd)



#pragma mark - 压缩图片
- (UIImage *)compressImageQuality:(CGSize )size toByte:(NSInteger)maxLength {
    
    UIImage *tmp =[self qmui_imageResizedInLimitedSize:size resizingMode:QMUIImageResizingModeScaleAspectFit];
    
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(tmp, compression);
    
    if (data.length < maxLength) {
        UIImage * image = [[UIImage alloc] initWithData:data];
        return image;
    }
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(tmp, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage * image = [[UIImage alloc] initWithData:data];
    return image;
}

@end
